﻿#region 引用
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using System.Threading;
using System.Diagnostics;

using DevComponents.AdvTree;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Rendering;
using Kxzz.Common;
using KxzzEntity.UsersEntity;
using Kaixin001.Common;
using Kaixin001.Images;
using KxzzEntity.FriendsEntity;
using Kxzz.Controls;
using Kxzz.IconUtil;
using Kaixin001.Msg;
using Kxzz.Enums;
using Entity.MsgEntity;
using Kaixin001.Friend;
using Kaixin001.Audio;
using Kaixin001.XmlUtil;
#endregion

namespace Kxzz
{
    public partial class frmMain : DevComponents.DotNetBar.Office2007RibbonForm
    {
        #region 变量
        private bool m_ColorSelected = false;
        private bool exit = false;
        private bool logout = false;
        private ShowIconMode showIconMode = ShowIconMode.MessageMsg;
        private IniHelper iniHelper = new IniHelper(Application.StartupPath + "//Config//config.ini");
        private IconHelper iconHelper = new IconHelper();
        private MsgHelper msgHelper = new MsgHelper(Init.Kaixin001Helper);
        private Dictionary<FriendEntity, SuperTooltipInfo> dicStis = new Dictionary<FriendEntity, SuperTooltipInfo>();
        private delegate void delegateThreadPoolSetTooltip(object o);
        public ClassForms forms = new ClassForms();

        private Node m_LastMouseOverNode = null;
        /// <summary>
        /// 窗体默认样式
        /// </summary>
        private eOffice2007ColorScheme m_BaseColorScheme = eOffice2007ColorScheme.Blue;
        #endregion

        #region 改变窗体样式相关
        private void AppCommandTheme_Executed(object sender, EventArgs e)
        {
            ICommandSource source = sender as ICommandSource;
            if (source.CommandParameter is string)
            {
                switch (source.CommandParameter as string)
                {
                    case "Blue": m_BaseColorScheme = eOffice2007ColorScheme.Blue; break;
                    case "Black": m_BaseColorScheme = eOffice2007ColorScheme.Black; break;
                    case "Silver": m_BaseColorScheme = eOffice2007ColorScheme.Silver; break;
                    case "VistaGlass": m_BaseColorScheme = eOffice2007ColorScheme.VistaGlass; break;
                    default: m_BaseColorScheme = eOffice2007ColorScheme.Blue; break;
                }
                this.iniHelper.write("Setup", "skin", source.CommandParameter.ToString());
                eOffice2007ColorScheme colorScheme = (eOffice2007ColorScheme)Enum.Parse(typeof(eOffice2007ColorScheme), source.CommandParameter.ToString());
                // This is all that is needed to change the color table for all controls on the form
                ribbonMain.Office2007ColorTable = colorScheme;
            }
            else if (source.CommandParameter is Color)
            {
                RibbonPredefinedColorSchemes.ChangeOffice2007ColorTable(this, m_BaseColorScheme, (Color)source.CommandParameter);
            }
            this.Invalidate();
        }

        private void btnStyleCustom_SelectedColorChanged(object sender, EventArgs e)
        {
            // Indicate that color was selected for buttonStyleCustom_ExpandChange method
            m_ColorSelected = true; 
            btnStyleCustom.CommandParameter = btnStyleCustom.SelectedColor;
        }

        private void btnStyleCustom_ColorPreview(object sender, ColorPreviewEventArgs e)
        {
            RibbonPredefinedColorSchemes.ChangeOffice2007ColorTable(this, m_BaseColorScheme, e.Color);
        }

        private void btnStyleCustom_EnabledChanged(object sender, EventArgs e)
        {
            if (btnStyleCustom.Expanded)
            {
                // Remember the starting color scheme to apply if no color is selected during live-preview
                m_ColorSelected = false;
                m_BaseColorScheme = ((Office2007Renderer)GlobalManager.Renderer).ColorTable.InitialColorScheme;
            }
            else
            {
                if (!m_ColorSelected)
                {
                    ribbonMain.Office2007ColorTable = m_BaseColorScheme;
                }
            }
        }
        #endregion

        #region 构造函数及初始化
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            #region 设置皮肤
            if (this.iniHelper.read("Setup", "skin") != "")
            {
                eOffice2007ColorScheme colorScheme = (eOffice2007ColorScheme)Enum.Parse(typeof(eOffice2007ColorScheme), this.iniHelper.read("Setup", "skin"));
                ribbonMain.Office2007ColorTable = colorScheme;
            }

            this.Size = new System.Drawing.Size(Init.FormWidth, Init.FormHeight);
            //base.Location = new Point(
            //    Screen.PrimaryScreen.WorkingArea.Width - base.Width - 145,
            //    Screen.PrimaryScreen.WorkingArea.Height - base.Height - 40);
            base.Location = Init.initPoint;
            #endregion

            this.InitForm();
        }
        #endregion

        #region 界面操作

        #region Form操作
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //是否退出
            if (!this.exit)
            {
                if (this.WindowState == FormWindowState.Normal)
                {
                    this.Hide();
                    this.notifyIconMain.Visible = true;
                }
                e.Cancel = true;
            }
            else
            {
                if(e.CloseReason == CloseReason.ApplicationExitCall)
                {
                    Application.DoEvents();
                    Application.Exit();
                }
            }
        }

        private void frmMain_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Hide();
                this.notifyIconMain.Visible = true;
            }
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //不为更改用户状态，让程序结束
            this.notifyIconMain.Dispose();
            Init.setAttribute("Logout", this.logout);
        }
        #endregion

        #region 头顶设置菜单
        private void biChangeUser_Click(object sender, EventArgs e)
        {
            this.Logout();
        }

        private void biClose_Click(object sender, EventArgs e)
        {
            this.Exit();
        }

        private void biSetting_Click(object sender, EventArgs e)
        {
            OpenSettingForm();
        }
        #endregion

        #region 状态栏菜单
        private void tsmiHomePage_Click(object sender, EventArgs e)
        {
            Process.Start("http://www.9ikaixin.com");
        }

        private void tsmiExit_Click(object sender, EventArgs e)
        {
            this.Exit();
        }

        private void tsmiLogout_Click(object sender, EventArgs e)
        {
            this.Logout();
        }

        private void tsmiShowMainForm_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.TopMost = true;
            this.notifyIconMain.Visible = false;
        }

        private void tsmiAbout_Click(object sender, EventArgs e)
        {
            frmAboutBox fra = new frmAboutBox();
            fra.Show();
        }

        private void tsmiSetting_Click(object sender, EventArgs e)
        {
            OpenSettingForm();
        }
        #endregion

        #region Timer
        private void timerShowIcon_Tick(object sender, EventArgs e)
        {
            iconHelper.ShowMsg(this.notifyIconMain);
        }

        private void timerCheckOnlineAndMsg_Tick(object sender, EventArgs e)
        {
            try
            {
                #region 设置读取短消息时间
                if (Init.nomalSettingEntity != null)
                {
                    if (Init.nomalSettingEntity.ReceiveMessageInterval != this.timerCheckOnlineAndMsg.Interval)
                    {
                        this.timerCheckOnlineAndMsg.Interval = Init.nomalSettingEntity.ReceiveMessageInterval;
                    }
                }
                #endregion

                this.ShowMessageIcon();
            }
            catch (Exception ex)
            {
                ExceptionHelper.SaveLog("timerCheckOnlineAndMsg_Tick", ex);
            }
        }

        private void timerPlaySound_Tick(object sender, EventArgs e)
        {
            this.timerPlaySound.Stop();
            AudioHelper audioHelper = new AudioHelper();
            audioHelper.FileName = Init.NewMsgSound;
            audioHelper.play();
        }
        #endregion

        #region 图标操作
        private void notifyIconMain_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.csmStatusBar.Show();
            }
        }

        private void notifyIconMain_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (Init.queueNewMessages.Count > 0)
                {
                    MessageGroupEntity mge = Init.queueNewMessages.Dequeue();

                    if (Init.queueNewMessages.Count == 0)
                    {
                        this.EndShowIcon();
                    }

                    foreach (System.Windows.Forms.Form fo in forms)
                    {
                        if (fo.Name == mge.Uid)
                        {
                            frmSendMsg fsm = (frmSendMsg)fo;
                            fsm.Text = "与 " + mge.FriendName + "(" + mge.Uid + ") 对话";
                            fsm.Tag = mge;
                            fsm.Name = mge.Uid;
                            fsm.HasMessages = true;
                            fsm.TopLevel = true;
                            fsm.Activate();
                            return;
                        }
                    }
                    frmSendMsg f = new frmSendMsg(this);
                    forms.add(f);
                    if (mge != null)
                    {
                        f.Text = "与 " + mge.FriendName + "(" + mge.Uid + ") 对话";
                        f.Tag = mge;
                        f.Name = mge.Uid;
                        f.HasMessages = true;
                        f.TopMost = true;
                        f.Show();
                    }
                }
                else
                {
                    this.EndShowIcon();
                    MinimizedOrNormalThisForm();
                }
            }
            catch (Exception ex)
            {
                ExceptionHelper.SaveLog("notifyIconMain_DoubleClick", ex);
            }
        }
        #endregion

        #region ToolTrip
        private void superTooltipProfile_MarkupLinkClick(object sender, DevComponents.DotNetBar.MarkupLinkClickEventArgs e)
        {
            Init.Kaixin001Helper.ShowIE(e.HRef);
        }

        private void advTreeUsers_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Point point = e.Location;
                delegateThreadPoolSetTooltip dtpt = new delegateThreadPoolSetTooltip(this.ThreadPoolSetTooltip);
                this.BeginInvoke(dtpt, point);
                //ThreadPool.QueueUserWorkItem(dtpt, point);
            }
        }

        private void tooltipDisplayDelay_Tick(object sender, EventArgs e)
        {
            this.timerTooltipDisplayDelay.Stop();
            if (m_LastMouseOverNode != null)
            {
                this.ShowNodeTooltip(m_LastMouseOverNode);
            }
        }

        private void advTreeUsers_MouseLeave(object sender, EventArgs e)
        {
            //HideNodeTooltip();
            HideNodeTooltip();
            timerTooltipDisplayDelay.Stop();
        }
        #endregion

        #region TreeView操作

        private void advTreeUsers_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                ActivateOrCreateFormSend();
            }
            catch (Exception ex)
            {
                DevComponents.DotNetBar.MessageBoxEx.Show(
                           ex.Message,
                           "错误",
                           MessageBoxButtons.OK,
                           MessageBoxIcon.Information);
            }
        }

        private void advTreeUsers_AfterExpand(object sender, AdvTreeNodeEventArgs e)
        {
            if (e.Node.Parent == null)
            {
                e.Node.ImageIndex = 1;
            }
        }

        private void advTreeUsers_AfterCollapse(object sender, AdvTreeNodeEventArgs e)
        {
            if (e.Node.Parent == null)
            {
                e.Node.ImageIndex = 0;
            }
        }

        private void advTreeUsers_NodeClick(object sender, TreeNodeMouseEventArgs e)
        {
            if (e.Node.Parent == null)
            {
                bool Expanded = e.Node.Expanded;
                foreach (Node nd in this.advTreeUsers.Nodes)
                {
                    nd.Collapse();
                }
                if (Expanded)
                {
                    e.Node.CollapseAll();
                }
                else
                {
                    e.Node.Expand();
                }
            }
        }
        #endregion

        #endregion

        #region Private Method

        #region  设置好友详细信息
        /// <summary>
        /// 设置好友详细信息
        /// </summary>
        /// <param name="point"></param>
        private void ThreadPoolSetTooltip(Object point)
        {
            #region 设置详细信息
            Node node = this.advTreeUsers.GetNodeAt((Point)point);
            NodeSuperTooltipProvider sp = new NodeSuperTooltipProvider(node);
            try
            {
                if (node != null && node.Parent != null && node.Tag != null)
                {
                    NodeEntity nodeEntity = (NodeEntity)node.Tag;
                    nodeEntity.NodeSp = sp;
                    node.Tag = nodeEntity;

                    #region 获取好友信息设置详细资料显示
                    FriendEntity firend = nodeEntity.FriendInfo;
                    string userInfoFileName = ".\\" + Init.UserDataFolder + "\\" + firend.Uid + "\\UserInfo.xml";
                    string userLargeHead = ".\\" + Init.UserDataFolder + "\\" + firend.Uid + "\\" + Init.UserLargeUserHeadFileName;
                
                    firend = Init.AllFriendsDetail[firend.Uid];

                    if (File.Exists(userInfoFileName))
                    {
                        FriendEntity fe = XmlHelper.XmlDeserialize(userInfoFileName, typeof(FriendEntity)) as FriendEntity;
                        if (fe != null && !string.IsNullOrEmpty(fe.RealName))
                        {
                            firend = fe;
                        }
                        else
                        {
                            FriendHelper fh = new FriendHelper(Init.Kaixin001Helper.HttpSetting, Init.Kaixin001Helper.Cookies);
                            firend = fh.GetFirendDetailByUID(firend.Uid);
                            Init.AllFriendsDetail[firend.Uid] = firend;
                            XmlHelper.XmlSerialize(userInfoFileName, firend, typeof(FriendEntity));
                        }
                    }
                    else
                    {
                        FriendHelper fh = new FriendHelper(Init.Kaixin001Helper.HttpSetting, Init.Kaixin001Helper.Cookies);
                        firend = fh.GetFirendDetailByUID(firend.Uid);
                        Init.AllFriendsDetail[firend.Uid] = firend;
                        XmlHelper.XmlSerialize(userInfoFileName, firend, typeof(FriendEntity));
                    }

                    SuperTooltipInfo sti = new SuperTooltipInfo();
                    if (!File.Exists(userLargeHead))
                    {
                        ImagesHelper ih = new ImagesHelper();
                        ih.SaveImage(firend.Icon, userLargeHead);
                    }

                    sti.BodyImage = Image.FromFile(userLargeHead);

                    StringBuilder sb = new StringBuilder();
                    string sex = firend.Sex == 0 ? "男" : "女";
                    sb.Append("性别：" + sex + "\n");
                    sb.Append("家乡：" + firend.HomeTown + "\n");
                    sb.Append("现居地：" + firend.LiveCity + "\n");
                    sb.Append("生日：" + firend.Birthday + "\n");
                    sb.Append("关系：" + firend.RelationShip + "\n");

                    sti.BodyText = sb.ToString();
                    sti.HeaderText = firend.RealName + "的资料";
                    sti.FooterText = "<a href=\"http://www.kaixin001.com/set/detail.php?uid=" + firend.Uid + "\">详细资料</a>";
                    sti.FooterImage = Properties.Resources.info;
                    this.superTooltipProfile.SetSuperTooltip(sp, sti);
                    #endregion
                }
            }
            catch (Exception ex)
            {
                SuperTooltipInfo sti = new SuperTooltipInfo();
                sti.BodyText = ex.Message;
                sti.HeaderText = "错误";
                sti.FooterText = "<a href=\"http://www.9ikaixin.com\">就爱开心网</a>";
                sti.FooterImage = Properties.Resources.info;
                this.superTooltipProfile.SetSuperTooltip(sp, sti);
            }
            finally
            {
                if (node != null && node.Parent != null && node.Tag != null)
                {
                    this.m_LastMouseOverNode = node;
                    this.timerTooltipDisplayDelay.Start();
                }
            }
            #endregion
        }
        /// <summary>
        /// 显示好友信息
        /// </summary>
        /// <param name="node"></param>
        private void ShowNodeTooltip(Node node)
        {
            if (node.Tag == null)
            {
                return;
            }

            NodeEntity nodeEntity = (NodeEntity)node.Tag;
            NodeSuperTooltipProvider sp = nodeEntity.NodeSp;
            if (sp != null)
            {
                sp.Show();
                m_LastMouseOverNode = node;
            }
        }

        private void HideNodeTooltip()
        {
            if (m_LastMouseOverNode != null)
            {
                NodeEntity nodeEntity = (NodeEntity)m_LastMouseOverNode.Tag;
                NodeSuperTooltipProvider sp = nodeEntity.NodeSp;
                if (sp != null)
                {
                    sp.Hide();
                    m_LastMouseOverNode = null;
                }
            }
        }
        #endregion

        private void OpenSettingForm()
        {
            frmSetting formSetting = new frmSetting();
            formSetting.Show();
        }

        /// <summary>
        /// 窗口最小化或者最大化
        /// </summary>
        private void MinimizedOrNormalThisForm()
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {
                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.notifyIconMain.Visible = false;
            }
        }

        /// <summary>
        /// 初始化好友信息
        /// </summary>
        private void InitFriends()
        {
            this.advTreeUsers.Nodes.Clear();
            int intAllFriendCount =  Init.AllFriends.Count;
            int intOnlineFirendsCount = Init.OnlineFriends.Count;
            List<Node> listOffLineFriends = new List<Node>();

            #region 全部好友
            Node treeNAll = new Node();
            treeNAll.Text = "全部好友(" + intOnlineFirendsCount.ToString() + "/" + intAllFriendCount.ToString() + ")";
            treeNAll.ImageIndex = 0;
            for (int i = 0; i < Init.AllFriends.Count; i++)
            {
                bool blnOnline = false;
                FriendEntity friend = Init.AllFriends[i];
                Node tnFriend = new Node();
                tnFriend.Text = friend.RealName;

                NodeEntity nodeEntity = new NodeEntity();
                nodeEntity.FriendInfo = friend;

                tnFriend.Tag = nodeEntity;

                Image image = Kxzz.Properties.Resources.OffLine;

                for (int k = 0; k < Init.OnlineFriends.Count; k++)
                {
                    if (friend.Uid == Init.OnlineFriends[k].Uid)
                    {
                        if (!File.Exists(friend.LocalIcon))
                        {
                            ImagesHelper imagesHelper = new ImagesHelper();
                            imagesHelper.SaveImage(friend.Icon, friend.LocalIcon, new Size(20, 20));
                        }
                        blnOnline = true;
                        image = Image.FromFile(friend.LocalIcon); break;
                    }
                    else
                    {
                        image = Kxzz.Properties.Resources.OffLine;
                        blnOnline = false;
                    }
                }

                tnFriend.Image = image;

                if (!blnOnline)
                {
                    listOffLineFriends.Add(tnFriend);
                }
                else
                {
                    treeNAll.Nodes.Add(tnFriend);
                }
            }

            treeNAll.Nodes.AddRange(listOffLineFriends.ToArray());

            this.advTreeUsers.Nodes.Add(treeNAll);
            listOffLineFriends.Clear();
            #endregion

            #region 分组好友
            for (int i = 0; i < Init.FriendGroups.Count; i++)
            {
                FriendGroupEntity friendGroup = Init.FriendGroups[i];
                Node tnGroup = new Node();
                int intGroupFirendsCount = friendGroup.Friends.Count;
                int intGroupOnlineFriendsCount = 0;

                for (int j = 0; j < friendGroup.Friends.Count; j++)
                {
                    bool blnOnline = false;
                    FriendEntity friend = friendGroup.Friends[j];
                    Node tnFriend = new Node();
                    tnFriend.Text = friend.RealName;

                    NodeEntity nodeEntity = new NodeEntity();
                    nodeEntity.FriendInfo = friend;

                    tnFriend.Tag = nodeEntity;

                    Image image = Kxzz.Properties.Resources.OffLine;

                    for (int k = 0; k < Init.OnlineFriends.Count; k++)
                    {
                        if (friend.Uid == Init.OnlineFriends[k].Uid)
                        {
                            if (!File.Exists(friend.LocalIcon))
                            {
                                ImagesHelper imagesHelper = new ImagesHelper();
                                imagesHelper.SaveImage(friend.Icon, friend.LocalIcon, new Size(20, 20));
                            }
                            blnOnline = true;
                            intGroupOnlineFriendsCount++;
                            image = Image.FromFile(friend.LocalIcon); break;

                        }
                        else
                        {
                            blnOnline = false;
                            image = Kxzz.Properties.Resources.OffLine;
                        }
                    }

                    tnFriend.Image = image;
                    if (blnOnline)
                    {
                        tnGroup.Nodes.Add(tnFriend);
                    }
                    else
                    {
                        listOffLineFriends.Add(tnFriend);
                    }
                }

                tnGroup.Text = friendGroup.GroupName + "(" + intGroupOnlineFriendsCount.ToString() + "/" + intGroupFirendsCount.ToString() + ")";
                tnGroup.ImageIndex = 0;
                tnGroup.Nodes.AddRange(listOffLineFriends.ToArray());
                this.advTreeUsers.Nodes.Add(tnGroup);
                listOffLineFriends.Clear();
            }
            #endregion
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void InitForm()
        {
            //获取最后登录用户头像
            Image image = Image.FromFile(iniHelper.read("UserHead", "LastLoginUserHead"));

            //尺寸缩小
            if (image != null)
            {
                image = image.GetThumbnailImage(50, 50, null, new IntPtr());
                this.reflectionImagePhoto.Image = image;
            }

            //显示姓名
            this.lblName.Text = Init.Kaixin001Helper.User.Name;

            //显示状态
            this.lblStatus.Text = Init.Kaixin001Helper.User.Status;

            this.notifyIconMain.Text = "开心猪猪-" + this.lblName.Text;

            SuperTooltipInfo sti = new SuperTooltipInfo();
            sti.BodyImage = image;
            StringBuilder sb = new StringBuilder();
            sb.Append("姓名：" + Init.Kaixin001Helper.User.Name + "\n");
            sb.Append("性别：" + Init.Kaixin001Helper.User.Sex + "\n");
            sb.Append("家乡：" + Init.Kaixin001Helper.User.Home + "\n");
            sb.Append("现居地：" + Init.Kaixin001Helper.User.Live + "\n");
            sti.BodyText = sb.ToString();
            sti.HeaderText = "我的资料";
            sti.FooterText = "<a href=\"http://www.9ikaixin.com\">就爱开心网</a>";
            sti.FooterImage = Properties.Resources.info;

            this.superTooltipProfile.SetSuperTooltip(this.reflectionImagePhoto, sti);

            //初始化好友列表
            this.InitFriends();
        }

        /// <summary>
        /// 初始化常规设置
        /// </summary>
        private void InitNomalSetting()
        {
            if (Init.nomalSettingEntity.AutoReceiveMessage)
            {
                this.timerCheckOnlineAndMsg.Enabled = true;
                this.timerCheckOnlineAndMsg.Interval = Init.nomalSettingEntity.ReceiveMessageInterval;
            }
            else
            {
                this.timerCheckOnlineAndMsg.Enabled = false;
            }
        }

        /// <summary>
        /// 更改用户
        /// </summary>
        private void Logout()
        {
            //真正退出
            this.exit = true;
            //注销方式退出
            this.logout = true;
            try
            {
                Init.Kaixin001Helper.Exit();
                Init.ExitAndClear();
            }
            catch (Exception)
            { }
            finally
            {
                this.Close();
            }
        }

        /// <summary>
        /// 退出程序
        /// </summary>
        private void Exit()
        {
            //真正执行退出操作
            this.exit = true;
            try
            {
                Init.Kaixin001Helper.Exit();
                Init.ExitAndClear();
            }
            catch (Exception)
            { }
            finally
            {
                this.Close();
            }
        }

        /// <summary>
        /// 激活或创建新的消息发送窗体
        /// </summary>
        private void ActivateOrCreateFormSend()
        {
            if (this.advTreeUsers.SelectedNode.Parent != null)
            {
                NodeEntity nodeEntity = this.advTreeUsers.SelectedNode.Tag as NodeEntity;
                FriendEntity friend = nodeEntity.FriendInfo;

                if (friend != null)
                {
                    foreach (System.Windows.Forms.Form fo in forms)
                    {
                        if (fo.Name == friend.Uid)
                        {
                            fo.Activate();
                            fo.TopLevel = true;
                            return;
                        }
                    }
                    frmSendMsg f = new frmSendMsg(this);
                    forms.add(f);
                    if (friend != null)
                    {
                        f.Text = "与 " + friend.RealName + "(" + friend.Uid + ") 对话";
                        f.Tag = nodeEntity.FriendInfo;
                        f.Name = friend.Uid;
                        f.HasMessages = false;
                        f.TopMost = true;
                        f.Show();
                    }
                }
            }
        }

        /// <summary>
        /// 检查是否有新消息
        /// </summary>
        private void CheckMsg()
        {
            Init.Kaixin001Helper.User = msgHelper.GetMsgCount(Init.Kaixin001Helper.User);
            if (Init.Kaixin001Helper.User.MessageCount > 0 )
            {
                this.showIconMode = ShowIconMode.MessageMsg;
                Init.NewMessages = msgHelper.GetNewMessage(Init.Kaixin001Helper.User);

                foreach (MessageGroupEntity mge in Init.NewMessages)
                {
                    Init.queueNewMessages.Enqueue(mge);
                    this.timerPlaySound.Start();
                }
                this.timerShowIcon.Enabled = true;
            }
        }

        /// <summary>
        /// 显示图标
        /// </summary>
        private void ShowMessageIcon()
        {
            switch (this.showIconMode)
            {
                case ShowIconMode.MessageMsg:
                    this.showIconMode = ShowIconMode.MessageMsg;
                    this.CheckMsg();
                    break;
                default:
                    this.showIconMode = ShowIconMode.MessageMsg;
                    this.CheckMsg();
                    break;
            }
        }

        /// <summary>
        /// 关闭显示图标
        /// </summary>
        private void EndShowIcon()
        {
            this.timerShowIcon.Enabled = false;
            this.notifyIconMain.Icon = Properties.Resources.Kxzz16x16;
        }
        #endregion  

        private void timerGetGardenInfo_Tick(object sender, EventArgs e)
        {
            //bllGarden.Start();
        }
    }
}
